package com.five.taotao.guide_mine;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.five.taotao.Application.MyApplication;
import com.five.taotao.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class PersonalInforActivity extends AppCompatActivity {
    /* 头像文件 */
   private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";

    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int output_X = 480;
    private static int output_Y = 480;

    //新建文件夹 先选好路径 再调用mkdir函数 现在是根目录下面的Phone文件夹
    File nf = new File(Environment.getExternalStorageDirectory()+"/Phone");
    //在根目录下面的ASk文件夹下 创建sctx.jpg文件
    File f = new File(Environment.getExternalStorageDirectory()+"/Phone", "sctx.jpg");

    FileOutputStream out = null;
    @BindView(R.id.tx)
    ImageView tx;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.zy)
     TextView zy;
   MyApplication application;
    int index=0;
    int index1=0;
    String[] items={"男","女"};
    String[] item={"学生", "初入社会", "资深工作党","辣妈"};
    private SharedPreferences sharedPreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_infor);
        ButterKnife.bind(this);
        application=((MyApplication)getApplicationContext());
        nf.mkdir();
        //从本地中读取该文件，然后设置接收
       application.setBitmap(getDiskBitmap(f.getPath()));
        sharedPreferences=getSharedPreferences("setup", MODE_PRIVATE);
        index=sharedPreferences.getInt("which", index);
        index1=sharedPreferences.getInt("which1", index1);
        sex.setText(items[index]);
        zy.setText(item[index1]);
    }

    @Override
    protected void onStart() {
        super.onStart();
        application.setBitmap(getDiskBitmap(f.getPath()));
        Log.i("path", f.getPath());
        if (application.bitmap() != null) {
            tx.setImageBitmap(application.bitmap());
        }
    }

    @OnClick(R.id.back)
    public  void back(View v){
        finish();
    }

    @OnClick(R.id.tx)
    public  void  headr(View v){
        View view= LayoutInflater.from(this)
                .inflate(R.layout.activity_phone,null,false);
        final PopupWindow popupWindow=new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT );

        //拍照
        view.findViewById(R.id.phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choseHeadImageFromCameraCapture();
            }
        });
        //从相册中挑选
        view.findViewById(R.id.xc).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choseHeadImageFromGallery();
            }
        });
        //取消
        view.findViewById(R.id.buttonCamera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x00000000);
        popupWindow.setBackgroundDrawable(dw);
        backgroundAlpha(this, 0.5f);//0.0-1.0
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(PersonalInforActivity.this, 1f);
            }
        });
        popupWindow.showAtLocation(v,
                Gravity.BOTTOM,
                0,
                0);
        popupWindow.showAsDropDown(v);
    }

    @OnClick(R.id.sex)
    public  void sexChoice(View v){
        AlertDialog.Builder bd=new AlertDialog.Builder(this);
        bd.setTitle("性别选择")
                .setSingleChoiceItems(items, index, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sex.setText(items[which]);
                        SharedPreferences.Editor editor=sharedPreferences.edit();
                        editor.putInt("which",which);
                        editor.commit();
                    }
                })
                .setNegativeButton("取消",null);
        bd.show();
    }

    @OnClick(R.id.zy)
    public  void  zyChoice(View v){
        AlertDialog.Builder bd=new AlertDialog.Builder(this);
        bd.setTitle("选择你的职业")
                .setSingleChoiceItems(item, index1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       zy.setText(item[which]);
                        SharedPreferences.Editor editor=sharedPreferences.edit();
                        editor.putInt("which1",which);
                        editor.commit();
                    }
                })
                .setNegativeButton("取消",null);
        bd.show();
    }

    @OnClick(R.id.item7)
    public  void address(View view){
        Intent intent = new Intent(this,AddAdressActivity.class);
        startActivity(intent);
    }
    //点击退出登录
    @OnClick(R.id.btn)
    public void logout(View view){
        //将本地userid置空
        SharedPreferences sp=getSharedPreferences("user",MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString("userId","");
        editor.commit();
        MyApplication.userId="";
        //同时返回到未登录状态的页面
//        Intent intent = getIntent();
//        setResult(2, intent);
        finish();
    }
    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity context, float bgAlpha)
    {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }
    // 从本地相册选取图片作为头像
    private void choseHeadImageFromGallery() {
        Intent intentFromGallery = new Intent();
        // 设置文件类型
        intentFromGallery.setType("image/*");
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);
    }

    // 启动手机相机拍摄照片作为头像
    private void choseHeadImageFromCameraCapture() {
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // 判断存储卡是否可用，存储照片文件
        if (hasSdcard()) {
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                    .fromFile(new File(Environment
                            .getExternalStorageDirectory(), IMAGE_FILE_NAME)));
        }

        startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {

        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
//            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }

        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
                cropRawPhoto(intent.getData());
                break;
            case CODE_CAMERA_REQUEST:
                if (hasSdcard()) {
                    File tempFile = new File(
                            Environment.getExternalStorageDirectory(),
                            IMAGE_FILE_NAME);
                    cropRawPhoto(Uri.fromFile(tempFile));
                } else {
                    Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG)
                            .show();
                }
                break;
            case CODE_RESULT_REQUEST:
                if (intent != null) {
                    setImageToHeadView(intent);
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, intent);
    }

    /**
     * 裁剪原始的图片
     */
    public void cropRawPhoto(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", output_X);
        intent.putExtra("outputY", output_Y);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CODE_RESULT_REQUEST);
    }

    /**
     * 提取保存裁剪之后的图片数据，并设置头像部分的View
     */
    private void setImageToHeadView(Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
           // tx.setImageBitmap(photo);
            //将图片以流的形式存在本地文件下
            try {
               //打开输出流 将图片数据填入文件中
                out = new FileOutputStream(f);
                photo.compress(Bitmap.CompressFormat.PNG, 90, out);
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 有存储的SDCard
            return true;
        } else {
            return false;
        }
    }

    /**
     * 从本地获取图片
     * @param pathString 文件路径
     * @return 图片
     */
    public Bitmap getDiskBitmap(String pathString)
    {
        Bitmap bitmap = null;
        try
        {
            File file = new File(pathString);
            if(file.exists())
            {
                bitmap = BitmapFactory.decodeFile(pathString);

            }
        } catch (Exception e)
        {
        }
        return bitmap;
    }
}
